package com.example.productserver.exception;

import com.example.productserver.menu.StatusCode;
import com.example.productserver.result.ResultBase;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler({Exception.class})
    @ResponseBody
    public ResultBase handleBindExceptionException(Exception ex) {

        ResultBase resultBase = new ResultBase();
        resultBase.setCode(StatusCode.ERROR);
        resultBase.setSuccess(false);
        if (ex instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException manvex = (MethodArgumentNotValidException) ex;
            FieldError fieldError = manvex.getBindingResult().getFieldError();
            resultBase.setMessage(fieldError.getDefaultMessage());
        } else {
            ex.printStackTrace();
            resultBase.setMessage("操作失败");
        }
        return resultBase;
    }


    @ExceptionHandler({CustomException.class})
    @ResponseBody
    public ResultBase handleBindExceptionCustomException(CustomException ex) {
        ResultBase resultBase = new ResultBase();
        resultBase.setCode(ex.getStatusCode());
        resultBase.setSuccess(false);
        resultBase.setMessage(ex.getMessage());
        return resultBase;
    }

}
